package com.mk.ssm.web;

import com.mk.ssm.bean.dto.BaseResult;
import com.mk.ssm.bean.entity.User;
import com.mk.ssm.enums.ResultEnum;
import com.mk.ssm.exception.BizException;
import com.mk.ssm.service.RoleService;
import com.mk.ssm.service.UserService;
import com.mk.ssm.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>Resource: yankee
 * <p>Date: 17-4-3
 * <p>Version: 1.0
 * 用户管理
 */
@Api(value = "UserController",description = "用户控制器",consumes = "application/json")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;


    /**
     * 添加用户信息
     * @param user  用户
     * @return  返回用户信息
     */
    @ApiOperation(value = "添加用户",notes = "传入User对象进行添加",response = BaseResult.class)
    @ApiImplicitParam(name = "用户",value = "user",required = true,dataType = "BaseResult<User>",paramType = "User")
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public BaseResult<User> createUser(@RequestBody(required = false) User user) {
        BaseResult<User> result = null;
        if(user != null){
            Integer res = userService.createUser(user);
            if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM04) {
                User user1 = userService.findByUsername(user.getUsername());
                user1.setPassword(null);
                user1.setSalt(null);
                result = new BaseResult<User>(true, user1);
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM01){
                result = new BaseResult<User>(false,"添加用户时信息缺少，请补全信息！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM02){
                result = new BaseResult<User>(false,"权限不足！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM03){
                result = new BaseResult<User>(false,"传入了错误的参数！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM05){
                result = new BaseResult<User>(false,"你输入的用户名已存在，请重新设置用户名！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM06){
                result = new BaseResult<User>(false,"添加用户时信息缺少，请补全信息！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM07){
                result = new BaseResult<User>(false,"新增的用户名不可使用中文！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM10){
                result = new BaseResult<User>(false,"添加时传入的用户姓名中不能存在%！");
            }else{
                result = new BaseResult<User>(false,"添加用户信息失败！");
            }
        }else{
            result = new BaseResult<User>(false,"需要添加的用户信息不可为空！");
        }
        return result;
    }

    /**
     * 根据id来获取其单个的用户信息
     * @param id
     * @param username
     * @return
     */
    @ApiOperation(value = "获取单个用户",notes = "传入用户id来获取用户",response = BaseResult.class)
    @ApiImplicitParam(name = "用户id/username",value = "id/username",required = true,dataType = "BaseResult<User>",paramType = "User")
    @RequestMapping(value = "/findByIdOrUsername",method = RequestMethod.GET)
    public BaseResult<User> findUserByIdOrUsername(@RequestParam(value = "id",required = false) Long id,
                                                   @RequestParam(value = "username",required = false) String username) {
        BaseResult<User> result = null;
//        if(id == null){
//            result = new BaseResult<User>(false,"获取的id值不可为空！");
//        }else {
        User user = new User();
        if(id != null && (username == null || "".equals(username))){
            user = userService.findOne(id);
        }else if(id == null && username != null && !"".equals(username)){
            user = userService.findByUsername(username);
        }else if(id != null && username != null && !"".equals(username)){
            user = userService.findOne(id);
        }else{
            user = null;
        }

        if(user != null){
            user.setSalt(null);
            user.setPassword(null);
            result = new BaseResult<User>(true,user);
        }else{
            result = new BaseResult<User>(false,"查询用户信息失败！");
        }
//        }
        return result;
    }

    /**
     * 修改用户信息  返回修改好的用户
     * @param user  需要修改的用户
     * @return
     */
    @ApiOperation(value = "修改用户",notes = "传入User对象进行添加",response = BaseResult.class)
    @ApiImplicitParam(name = "用户",value = "user",required = true,dataType = "BaseResult<User>",paramType = "User")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public BaseResult<User> updateUser(@RequestBody(required = false) User user) {
        BaseResult<User> result = null;
        if(user != null) {
            Integer res = userService.updateUser(user);
            if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM04) {
                User user1 = userService.findOne(user.getId());
                user1.setSalt(null);
                user1.setPassword(null);
                result = new BaseResult<User>(true, user1);
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM01){
                result = new BaseResult<User>(false,"传入的参数类型有误！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM02){
                result = new BaseResult<User>(false,"权限不足！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM03){
                result = new BaseResult<User>(false,"修改用户信息失败！");
            } else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM05){
                result = new BaseResult<User>(false,"传入需要修改的用户不存在！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM06){
                result = new BaseResult<User>(false,"修改用户信息时传入的信息有误！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM07){
                result = new BaseResult<User>(false,"修改用户信息时传入的用户名不能使用中文！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM10){
                result = new BaseResult<User>(false,"修改时传入的用户姓名中不能存在%！");
            }else{
                result = new BaseResult<User>(false,"修改用户信息失败！");
            }
        }else{
            result = new BaseResult<User>(false,"需要修改的用户不可为空！");
        }
        return result;
    }

    /**
     * 删除用户信息
     * @param id  用户id
     * @return 将用户的状态修改为不可用状态
     */
    @ApiOperation(value = "删除用户",notes = "传入用户id来删除（将able属性值修改为0）",response = BaseResult.class)
    @ApiImplicitParam(name = "用户",value = "id",required = true,dataType = "BaseResult<User>",paramType = "java.lang.Long")
    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public BaseResult<User> deleteUser(@RequestParam(value = "id",required = false) Long id) {
        BaseResult<User> result = null;
        if(id == null){
            result = new BaseResult<User>(false,"你要删除的用户不存在！");
        }else{
            Integer res = userService.deleteUser(id);
            if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM04){
                User user = userService.findOne(id);
                result = new BaseResult<User>(true,user);
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM03){
                result = new BaseResult<User>(false,"删除用户信息失败！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM01){
                result = new BaseResult<User>(false,"超级管理员信息不可删除！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM02){
                result = new BaseResult<User>(false,"删除的用户信息不存在！");
            }else{
                result = new BaseResult<User>(false,"删除用户信息失败！");
            }
        }
        return result;
    }

//
//    @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
//    public String showChangePasswordForm(@Param("id") Long id, Model model) {
//        model.addAttribute("user", userService.findOne(id));
//        model.addAttribute("op", "修改密码");
//        return "user/changePassword";
//    }

    /**
     * 修改用户密码
     * @param user 传包含id及密码的用户
     * @return
     */
//    @ApiOperation(value = "修改用户密码",notes = "传入id及修改后的密码",response = BaseResult.class)
//    @ApiImplicitParam(name = "用户",value = "user",required = true,dataType = "BaseResult<User>",paramType = "User")
//    @RequestMapping(value = "/changePassword",method = RequestMethod.POST)
//    public BaseResult<User> changePassword(@RequestBody(required = false)User user) {
//        BaseResult<User> result = null;
//        System.out.println("**********************");
//        System.out.println("id=" + user.getId());
//        System.out.println("oldPassword=" + user.getOldPassword());
//        System.out.println("password=" + user.getPassword());
//        System.out.println("*************************");
//        if(user != null) {
//            Integer res = userService.changePassword(user.getId(), user.getOldPassword(),user.getPassword());
//            if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM04) {
//                User user1 = userService.findOne(user.getId());
//                user1.setPassword(null);
//                user1.setSalt(null);
//                logService.addLog("用户名为" + user1.getUsername() + "修改了密码");
//                result = new BaseResult<User>(true, user1);
//            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM03){
//                result = new BaseResult<User>(false,"修改用户密码失败！");
//            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM01){
//                result = new BaseResult<User>(false,"修改密码时传入的密码不可为空！");
//            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM02){
//                result = new BaseResult<User>(false,"修改密码时传入的用户编号有误！");
//            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM05){
//                result = new BaseResult<User>(false,"传入的原密码有误！");
//            }else{
//                result = new BaseResult<User>(false,"修改用户密码失败！");
//            }
//        }else{
//            result = new BaseResult<User>(false,"修改密码时传入的参数不可为空！");
//        }
//        return result;
//    }

    /**wang
     * 修改用户密码
     * @param user 传包含id及密码的用户
     * @return
     */
    @ApiOperation(value = "修改用户密码",notes = "传入id及修改后的密码",response = BaseResult.class)
    @ApiImplicitParam(name = "用户",value = "user",required = true,dataType = "BaseResult<User>",paramType = "User")
    @RequestMapping(value = "/changePassword",method = RequestMethod.POST)
    public BaseResult<User> changePassword(@RequestBody(required = false)User user) {
        BaseResult<User> result = null;
        System.out.println("**********************");
        System.out.println("id=" + user.getId());
        System.out.println("oldPassword=" + user.getOldPassword());
        System.out.println("password=" + user.getPassword());
        System.out.println("*************************");
        if(user != null) {
            Integer res = userService.passwordChange(user.getId(),user.getUsername(), user.getOldPassword(),user.getPassword());
            if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM04) {
                User user1 = userService.findOne(user.getId());
                user1.setPassword(null);
                user1.setSalt(null);
                result = new BaseResult<User>(true, user1);
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM03){
                result = new BaseResult<User>(false,"修改用户密码失败！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM01){
                result = new BaseResult<User>(false,"修改密码时传入的密码不可为空！");
            } else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM08){
                result = new BaseResult<User>(false,"登录名已存在！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM02){
                result = new BaseResult<User>(false,"修改密码时传入的用户编号有误！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM05){
                result = new BaseResult<User>(false,"传入的原密码有误！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM07){
                result = new BaseResult<User>(false,"登录名只能是字母/数字/下划线自由组合！");
            }else if(res == ResultUtil.RESULT_CONFIG.RESULT_NUM09){
                result = new BaseResult<User>(false,"登录名不能为空！");
            }
            else{
                result = new BaseResult<User>(false,"修改用户密码失败！");
            }
        }else{
            result = new BaseResult<User>(false,"修改密码时传入的参数不可为空！");
        }
        return result;
    }

//    private void setCommonData(Model model) {
//        model.addAttribute("roleList", roleService.findAll());
//    }

    /**
     * 优雅的异常分类：业务异常（捕获的XXService层抛出的业务异常）、非业务异常（系统异常）
     * @return json数据
     * 根据id或者用户名来查询用户信息
     */
    @ApiOperation(value = "查询多个用户",notes = "传入id或用户名模糊查询",response = BaseResult.class)
    @ApiImplicitParam(name = "id或者username或者空值",value = "id/Username/null",required = true,dataType = "BaseResult<List<User>>",paramType = "User")
    @RequestMapping(value = "/findUsers",method = RequestMethod.GET)
    public BaseResult<List<User>> findUsers(@RequestParam(value = "id",required = false) Long id,
                                            @RequestParam(value = "username",required = false) String username){
        BaseResult<List<User>> result = null;
        try {
            List<User> list = userService.findUsers(id,username);
            result = new BaseResult<List<User>>(true, list);
        } catch(BizException e){
            result = new BaseResult(false, e.getMessage());
        } catch(Exception e){
            result = new BaseResult(false, ResultEnum.INNER_ERROR.getMsg());
        }
        return result;
    }

    @ApiOperation(value = "根据部门查询用户信息",notes = "传入部门id或者用户姓名一起查询",response = BaseResult.class)
    @ApiImplicitParam(name = "组织编号及姓名模糊查询",value = "orgIdOrName",required = true,dataType = "Map<String,Object>",paramType = "UserAndOrg")
    @RequestMapping(value = "/findUsersByOrg",method = RequestMethod.GET)
    public Map<String,Object> findUsersByOrgIdAndName(@RequestParam(value = "orgId",required = false) Long orgId,
                                                      @RequestParam(value = "name",required = false) String name,
                                                      @RequestParam(value = "pageNumber",required = false) Integer pageNumber,
                                                      @RequestParam(value = "pageSize",required = false) Integer pageSize){
        Map<String,Object> map = new HashedMap();
        System.out.println("###################################");
        System.out.println("orgId = " + orgId);
        System.out.println("name = "+name);
        List<User> list = userService.findUsersByOrg(orgId,name,pageNumber,pageSize);
        if(name != null && !ResultUtil.haveName(name)) {
            map.put("total",0);
            map.put("rows",new ArrayList<User>());
        }else {
            map.put("total", userService.countNum(orgId, name));
            map.put("rows", list);
        }
//        if(list != null || list.size() > 0){
//            result = new BaseResult<List<UserAndOrg>>(true, list);
//        }else{
//            result = new BaseResult<List<UserAndOrg>>(false,"查询结果为空！");
//        }
        return map;
    }
}
